﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using ConsoleApp2;
using server;
using server.Tool;

namespace tcpserver
{
    public class SocketService
    {

        static Socket socketWatch = null;
        public void Create()
        {
            int port = 7788;
            IPAddress ip = IPAddress.Any;
            IPEndPoint ipe = new IPEndPoint(ip, port);

            //定义一个套接字用于监听客户端发来的消息，包含三个参数（IP4寻址协议，流式连接，Tcp协议） 
            socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //监听绑定的网络节点 
            socketWatch.Bind(ipe);
            //将套接字的监听队列长度限制为20 
            socketWatch.Listen(20);

            Thread threadwatch = new Thread(WatchConnecting);
            //将窗体线程设置为与后台同步，随着主线程结束而结束 
            threadwatch.IsBackground = true;
            //启动线程    
            threadwatch.Start();

            Console.WriteLine("服务器监听成功......，端口："+ 7788);
        }
        private  void WatchConnecting()
        {
            Socket connection = null;

            //持续不断监听客户端发来的请求    
            while (true)
            {
                try
                {
                    connection = socketWatch.Accept();
                    CheckServerStateTimer.Instance.ResetTimer();
                }
                catch (Exception ex)
                {
                    //提示套接字监听异常    
                    Console.WriteLine(ex.Message);
                    break;
                }

                //客户端网络结点号 
                string remoteEndPoint = connection.RemoteEndPoint.ToString();
               
               //添加客户端信息 

               //显示与客户端连接情况
               //  Console.WriteLine("\r\n[客户端\"" + remoteEndPoint + "\"建立连接成功！ 客户端数量：" + ClientConnectionItems.Count + "]");

               //获取客户端的IP和端口号 
               IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint).Address;
                int clientPort = (connection.RemoteEndPoint as IPEndPoint).Port;

                //让客户显示"连接成功的"的信息 
                string sendmsg = "";
                byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg);
                connection.Send(arrSendMsg);

                Console.WriteLine(sendmsg);

                //创建一个通信线程     
                Thread thread = new Thread(recv);
                //设置为后台线程，随着主线程退出而退出
                thread.IsBackground = true;
                //启动线程    
                thread.Start(connection);

                CreateQueueData.Instance.Start();
               
            }
        }
        private  void recv(object socketclientpara)
        {
            Socket socketServer = socketclientpara as Socket;

            while (true)
            {
                //创建一个内存缓冲区，其大小为1024*1024字节  即1M    
                byte[] arrServerRecMsg = new byte[1024 * 1024];
                //将接收到的信息存入到内存缓冲区，并返回其字节数组的长度   
                try
                {
                    int length = socketServer.Receive(arrServerRecMsg);

                    CheckServerStateTimer.Instance.ResetTimer();
                    //将机器接受到的字节数组转换为人可以读懂的字符串    
                    string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);

                    //Console.WriteLine(strSRecMsg);
                    //将发送的字符串信息附加到文本框txtMsg上    

                    ReveiveMessage(strSRecMsg, socketServer);
                    //Thread.Sleep(3000);
                    //socketServer.Send(Encoding.UTF8.GetBytes(""));
                    //发送客户端数据
                    if (length==0)
                    {
                        Console.WriteLine("客户端断开");
                        socketServer.Close();
                        break;
                    }
                    else
                    {
                        //Console.WriteLine("\r\n[客户端：" + socketServer.RemoteEndPoint + " 时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + "]\r\n" + strSRecMsg);
                    }
                  
                }
                catch (Exception)
                {
                    socketServer.Close();
                }
            }
        }

        private void ReveiveMessage(string strSRecMsg,Socket socketServer)
        {
            //硬件的信息
            if(strSRecMsg.ToUpper().Contains("CFG"))
            {
                string str = "SC#0  h]<?xml version='1.0' encoding='UTF-8'?><channel_overview><channel name='SharedMemory_1/Channel_1' unit='Unit'/><channel name='SharedMemory_1/Channel_2' unit='Unit'/><channel name='SharedMemory_2/Channel_1' unit='kN'/><channel name='SharedMemory_2/Channel_2' unit='mm'/></channel_overview>";
                byte[] bytes = ConverUtility.StringToBytes(str);
                List<byte> list = new List<byte>(bytes);
                list.Add(0x0A);
                list.Add(0x0D);
                socketServer.Send(list.ToArray());
            } 
            else if(strSRecMsg.ToUpper().Contains("RUN"))
            {
                string str = "RV#0";
                byte[] bytes = ConverUtility.StringToBytes(str);


                List<byte> list = new List<byte>(bytes);
                list.Add(0x0A);
                list.Add(0x0D);
                socketServer.Send(list.ToArray());
            }

            //获取的长度
            else if(strSRecMsg.ToUpper().Contains("OMP"))
            {
                string str = "NS#0";
                byte[] bytes = ConverUtility.StringToBytes(str);
                List<byte> list = new List<byte>(bytes);
                int length = CreateQueueData.Instance.GetDataLength();
                //Console.WriteLine("send length="+ length);


                byte[] hasbyte = BitConverter.GetBytes(length);
                Array.Reverse(hasbyte);
                list.AddRange(hasbyte);
                list.Add(0x0A);
                list.Add(0x0D);
                socketServer.Send(list.ToArray());

            }
            //获取数据
            else if(strSRecMsg.ToUpper().Contains("RMB"))
            {
                List<byte> result = new List<byte>();

                string str = strSRecMsg.Replace("RMB?","");
                str = str.Trim();
                int _length = int.Parse(str);

                Console.WriteLine("请求长度" + _length);
                List<byte> sendData = CreateQueueData.Instance.GetSendData(_length);
                if(sendData!=null && sendData.Count>0)
                {
                    socketServer.Send(sendData.ToArray());
                }
                //List<string> times = new List<string>();
                //uint time =  TestData._GetTimeStamp();
                //for (int i = 0; i < 1000; )
                //{
                //    byte[] bytes1 = TestData.GetDataByIndex(i, time);
                //    result.AddRange(bytes1);
                //    times.Add(TestData.time);
                //    i = i + 5;
                //}
                // socketServer.Send(TestData1.GetTest1());
                //List<byte> result =CreateDataService.Instance.Data;
               
               // CreateDataService.Instance.ClearData();

            }
        }


    }
}
